using System.Text;
using System.Xml;
using System.Reflection;
using System.IO;
using System.Windows.Forms;
using Christian.Helle.PocketNews.PocketPC.Utilities;

namespace Christian.Helle.PocketNews.PocketPC
{
    public sealed class Configuration
    {
        private static string config_file;
        private static string signature;

        public static string AppDirectory { get; private set; }

        public static bool Initialize()
        {
            AppDirectory = Path.GetDirectoryName(
                Assembly.GetExecutingAssembly().GetName().CodeBase);

            config_file = string.Format(
                "{0}\\Config.xml",
                AppDirectory);

            if (!File.Exists(config_file))
            {
                CreateConfigurationFile();

                using (frmFirstRun form = new frmFirstRun())
                {
                    if (form.ShowDialog() != DialogResult.OK)
                    {
                        File.Delete(config_file);
                        return false;
                    }
                }
            }

            LoadConfiguration();

            return true;
        }

        private static void CreateConfigurationFile()
        {
            XmlTextWriter writer = null;
            try
            {
                writer = new XmlTextWriter(config_file, Encoding.UTF8);

                writer.WriteStartDocument();
                writer.WriteStartElement("Configuration");

                writer.WriteElementString("NntpServer", "msnews.microsoft.com");
                writer.WriteElementString("CurrentNewsgroup", string.Empty);
                writer.WriteElementString("AutoEstablishConnection", bool.FalseString);
                writer.WriteElementString("UseGprs", bool.FalseString);
                writer.WriteElementString("MaxCount", "0");
                writer.WriteElementString("AutoCheckDuration", "15");
                writer.WriteElementString("SenderName", string.Empty);
                writer.WriteElementString("SenderEmail", string.Empty);
                writer.WriteElementString("Signature", string.Empty);
                writer.WriteElementString("CompressDb", bool.FalseString);
                writer.WriteElementString("AutoSaveDraft", bool.FalseString);
                writer.WriteElementString("AutoSaveDraftInterval", "1");
                writer.WriteElementString("AutoInsertSignature", bool.TrueString);
                writer.WriteElementString("NntpRequiresLogon", bool.FalseString);
                writer.WriteElementString("AccountName", string.Empty);
                writer.WriteElementString("Password", string.Empty);
                writer.WriteElementString("EnableTransitionEffects", bool.TrueString);
                writer.WriteElementString("DefaultTransitionEffect", "slide");

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }

        private static void LoadConfiguration()
        {
            XmlTextReader reader = null;
            string node = null;

            try
            {
                reader = new XmlTextReader(config_file);
                reader.Normalization = true;

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        node = reader.Name;
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        switch (node)
                        {
                            case "NntpServer":
                                NntpServer = reader.Value;
                                break;
                            case "CurrentNewsgroup":
                                CurrentNewsgroup = reader.Value;
                                break;
                            case "AutoEstablishConnection":
                                AutoEstablishConnection = bool.Parse(reader.Value);
                                break;
                            case "UseGprs":
                                UseGprs = bool.Parse(reader.Value);
                                break;
                            case "MaxCount":
                                MaxCount = int.Parse(reader.Value);
                                break;
                            case "AutoCheckDuration":
                                AutoCheckDuration = int.Parse(reader.Value);
                                break;
                            case "SenderName":
                                SenderName = reader.Value;
                                break;
                            case "SenderEmail":
                                SenderEmail = reader.Value;
                                break;
                            case "Signature":
                                Signature = reader.Value;
                                break;
                            case "CompressDb":
                                CompressDb = bool.Parse(reader.Value);
                                break;
                            case "AutoSaveDraft":
                                AutoSaveDraft = bool.Parse(reader.Value);
                                break;
                            case "AutoSaveDraftInterval":
                                AutoSaveDraftInterval = int.Parse(reader.Value);
                                break;
                            case "AutoInsertSignature":
                                AutoInsertSignature = bool.Parse(reader.Value);
                                break;
                            case "NntpRequiresLogon":
                                NntpRequiresLogon = bool.Parse(reader.Value);
                                break;
                            case "AccountName":
                                AccountName = reader.Value;
                                break;
                            case "Password":
                                Password = reader.Value;
                                break;
                            case "EnableTransitionEffects":
                                EnableTransitionEffects = bool.Parse(reader.Value);
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            finally
            {
                if (reader != null && reader.ReadState != ReadState.Closed)
                {
                    reader.Close();
                }
            }
        }

        public static void SaveChanges()
        {
            XmlDocument doc = null;
            try
            {
                doc = GetConfigAsXmlDocument();
                doc.GetElementsByTagName("NntpServer")[0].InnerText = NntpServer;
                doc.GetElementsByTagName("AutoEstablishConnection")[0].InnerText = AutoEstablishConnection.ToString();
                doc.GetElementsByTagName("UseGprs")[0].InnerText = UseGprs.ToString();
                doc.GetElementsByTagName("MaxCount")[0].InnerText = MaxCount.ToString(); ;
                doc.GetElementsByTagName("AutoCheckDuration")[0].InnerText = AutoCheckDuration.ToString();
                doc.GetElementsByTagName("SenderName")[0].InnerText = SenderName;
                doc.GetElementsByTagName("SenderEmail")[0].InnerText = SenderEmail;
                doc.GetElementsByTagName("CompressDb")[0].InnerText = CompressDb.ToString();
                doc.GetElementsByTagName("AutoInsertSignature")[0].InnerText = AutoInsertSignature.ToString();
                doc.GetElementsByTagName("NntpRequiresLogon")[0].InnerText = NntpRequiresLogon.ToString();
                doc.GetElementsByTagName("AccountName")[0].InnerText = AccountName;
                doc.GetElementsByTagName("Password")[0].InnerText = Password;
                doc.GetElementsByTagName("Signature")[0].InnerText = signature;
                doc.GetElementsByTagName("CurrentNewsgroup")[0].InnerText = CurrentNewsgroup;
                doc.GetElementsByTagName("EnableTransitionEffects")[0].InnerText = EnableTransitionEffects.ToString();
            }
            finally
            {
                var fi = new FileInfo(config_file);
                fi.Attributes = ~FileAttributes.ReadOnly;
                
                if (doc != null)
                    doc.Save(config_file);
            }
        }

        private static XmlDocument GetConfigAsXmlDocument()
        {
            XmlDocument doc = new XmlDocument();
            using (ConfigReader reader = new ConfigReader(config_file))
                doc.LoadXml(reader.Data);
            return doc;
        }

        public static string NntpServer { get; set; }

        public static string CurrentNewsgroup { get; set; }

        public static bool AutoEstablishConnection { get; set; }

        public static bool UseGprs { get; set; }

        public static int MaxCount { get; set; }

        public static int AutoCheckDuration { get; set; }

        public static string Signature
        {
            get { return signature; }
            set
            {
                signature = value;
                signature = signature.Replace("\n", "\r\n");
                signature = signature.Replace("\r\r", "\r");
            }
        }

        public static bool CompressDb { get; set; }

        public static string Sender
        {
            get { return string.Format("{0} <{1}>", SenderName, SenderEmail); }
        }

        public static string SenderName { get; set; }

        public static string SenderEmail { get; set; }

        public static bool AutoInsertSignature { get; set; }

        public static string AccountName { get; set; }

        public static string Password { get; set; }

        public static bool AutoSaveDraft { get; set; }

        public static int AutoSaveDraftInterval { get; set; }

        public static bool NntpRequiresLogon { get; set; }

        public static bool EnableTransitionEffects { get; set; }
    }
}
